﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Shared.Model;
using Shared.Method;
using Client;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace ModemWrite
{
    public partial class FormFactoryCheck : UserControl
    {
        private string _stationIp = null;
        private string _localIp = null;
        private int _localPort = 0;

        private string _modemIp = null;
        private string _modemUser = null;
        private string _modemPwd = null;

        //private string _ifWait = "0";

        private int _myFormNum = 0;

        private string _log = "";

        private object lockLog = new object();

        //所有的产品类型信息
        private List<Device_Type> _listType = null;

        private Task _runTack = null;

        public event Action<int> OnWrite;

        public FormFactoryCheck(
            string localIp, int localPort,
            string modemIp, string modemUser, string modemPwd,
            int formNum, List<Device_Type> listType, string stationIp = "127.0.0.1", string ifWait = "0")
        {
            _stationIp = stationIp;
            _localIp = localIp;
            _localPort = localPort;

            _modemIp = modemIp;
            _modemUser = modemUser;
            _modemPwd = modemPwd;

            _myFormNum = formNum;

            //_ifWait = ifWait;

            _listType = listType;
            if (string.IsNullOrEmpty(localIp)
                || string.IsNullOrEmpty(modemIp)
                || string.IsNullOrEmpty(modemUser)
                || string.IsNullOrEmpty(modemPwd)
                || localPort <= 1024)
            {
                //初始化的参数不正确
                MessageBox.Show(string.Format("窗口：{0}，初始化参数不正确", _myFormNum));
                this.Dispose();//销毁窗口
            }

            InitializeComponent();
        }

        /// <summary>
        /// 一个信息写入结束时操作
        /// </summary>
        private void FinallyDone(string mac = null, bool result = false, string state = null)
        {
            if (mac != null)//有一种情况不情况对应的xponSN
                PublicData.ListAddress.Remove(mac);

            Color colorText = Color.Black; //颜色
            string showText = state;//显示内容

            //修改显示内容
            if (result == false) { showText = "FAIL"; colorText = Color.Red; }
            else if (state == "E") { showText = "PASS"; colorText = Color.BlueViolet; }
            else if (state == "G") { showText = "PASS"; colorText = Color.Green; }

            //显示内容
            SetControlText(this.LabelTestState, showText, colorText);

            //判断光猫是否已经拔出了，如果拔出了，显示等待中
            while (true)
            {
                bool linkStatus = PingBaseClass.PingTest(_localIp, _modemIp);/*ArpBaseClass.IsIpEnabled(_localIp);*/
                if (linkStatus == false)
                    break;//没有连接，直接结束

                System.Threading.Thread.Sleep(500);
            }

            //SetTestResult(false, "WAIT");
            SetControlText(this.LabelTestState, "WAIT", Color.Black);

            SetTextBoxReadOnly(false);//设置textbox可用

            MacFocus();//清空mac/sn
        }


        private void MacFocus()
        {
            if (this.textBoxMAC.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                    this.textBoxMAC.Clear();
            }
        }

        private void SetTextBoxReadOnly(bool read = false)
        {
            if (this.textBoxMAC.InvokeRequired)
            {
                Action<bool> d = new Action<bool>(SetTextBoxReadOnly);
                Invoke(d, read);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                    this.textBoxMAC.ReadOnly = read;
            }
        }

        #region 自动获取MAC地址的出厂检查
        //private void FormFactoryCheck_Load(object sender, EventArgs e)
        //{
        //    _runTack=Task.Factory.StartNew(()=>
        //    {
        //        while (true)
        //        {
        //            //等待断开连接
        //            while (true)
        //            {
        //                if (PingBaseClass.PingTest(_localIp,_modemIp)==false) break;
        //                System.Threading.Thread.Sleep(500);
        //            }

        //            SetTestResult(false, "WAIT");

        //            while (true)
        //            {
        //                if (ArpBaseClass.IsIpEnabled(_localIp)) break;
        //                System.Threading.Thread.Sleep(500);
        //            }

        //            //检查光猫是否连接
        //            AppendRichTextBox("等待连接……");
        //            SetTestResult(true, "WAITFOR");
        //            //连续PING通4次才算连接上了

        //            int pingOkTimes = 0;
        //            for (int i = 0; i < 80; i++)
        //            {
        //                if (PingBaseClass.PingTest(_localIp, _modemIp))
        //                {
        //                    pingOkTimes++;
        //                    if (pingOkTimes >= 4)
        //                        break;
        //                }
        //                else
        //                {
        //                    pingOkTimes = 0;
        //                }
        //                //AppendRichTextBox("等待光猫连接……");
        //                //AppendRichTextBox("#", false);

        //                System.Threading.Thread.Sleep(500);
        //            }

        //            if (pingOkTimes < 4)
        //            {
        //                AppendRichTextBox("未能成功PING通光猫");
        //                continue;
        //            }

        //            _log = "";

        //            bool resetRet =FactotyCheck();

        //            SetTestResult(resetRet);//设置结果
        //        }
        //    });
        //}
        #endregion

        public void Stop()
        {
            _runTack?.Dispose();
        }

        private void FactotyCheck(string enterMac = null)
        {
            ClearText(this.richTextBoxMsg);

            if (string.IsNullOrEmpty(enterMac))//提供接口
            {
                SetControlText(this.labelWornMsg, "提示信息", false);

                enterMac = this.textBoxMAC.Text.Trim();

                _log = "";//保留扫描出错的LOG记录
            }

            OnWrite?.Invoke(_myFormNum);

            if (PublicData.ListAddress.ContainsKey(enterMac))
            {
                AppendRichTextBox("此MAC在其他窗口使用中……");
                FinallyDone();
                return;
            }
            else
            {
                PublicData.ListAddress.Add(enterMac, _myFormNum);
            }

            string msg = "";

            //检查光猫是否连接
            AppendRichTextBox("等待连接……");
            //SetTestResult(true, "WAITFOR");
            SetControlText(this.LabelTestState, "WAITFOR", Color.Black);
            //连续PING通4次才算连接上了

            int pingOkTimes = 0;
            for (int i = 0; i < 80; i++)
            {
                if (PingBaseClass.PingTest(_localIp, _modemIp))
                {
                    pingOkTimes++;
                    if (pingOkTimes >= 4)
                        break;
                }
                else
                {
                    pingOkTimes = 0;
                }

                System.Threading.Thread.Sleep(500);
            }

            if (pingOkTimes < 4)
            {
                AppendRichTextBox("未能成功PING通光猫");
                FinallyDone(enterMac);
                return;
            }

            //显示正在测试当中
            //SetTestResult(false, "TESTING");
            SetControlText(this.LabelTestState, "TESTING", Color.Black);

            //光猫真实MAC
            string realMac = string.Empty;
            for (int i = 0; i < 3; i++)
            {
                realMac = ArpBaseClass.GetMacFromIp(_localIp, _modemIp);
                if (!string.IsNullOrEmpty(realMac) && realMac.Length == 12) break;
            }

            //AppendRichTextBox("光猫内部MAC：" + realMac);

            //获取产品的版本
            Device_Data device = GetProductEdition(realMac);

            if (device == null)
            {
                AppendRichTextBox("获取Device_Data产品数据失败……");

                FinallyDone(enterMac);
                return;
            }

            //检查出厂信息
            //获得产品类型的测试数据
            Device_Type deviceType = GetDeviceType(device.DeviceType, device.HW_PROVINCE_NAME);

            if (deviceType == null)
            {
                AppendRichTextBox("未能获得产品类型对应的检测信息，检测失败");
                FinallyDone(enterMac);
                return;
            }

            //获取了MAC地址，将其写在界面上
            if (string.IsNullOrEmpty(realMac) == false)
            {
                AppendRichTextBox("获取MAC地址成功_ARP，MAC：" + realMac);
            }

            //判断是移动还是电信版本
            //bool isCmcc = false;

            //if (device.DeviceType == "PT924E") isCmcc = true;

            AppendRichTextBox("等待27秒……");
            System.Threading.Thread.Sleep(27000);

            //网页数据重测次数3次，等待5秒
            string httpMsg = null;

            for (int i = 0; i < 5; i++)
            {
                AppendRichTextBox("等待时间15秒……");
                System.Threading.Thread.Sleep(15000);

                if (device.DeviceType.Contains("CMCC"))
                {
                    Shared.SoftMethod.SoftShared.LoginCMCC(_modemIp, _localIp, _localPort, ref portOffset, device.HW_PROVINCE_NAME);
                }

                httpMsg = GetModemMessage(deviceType);
                if (string.IsNullOrEmpty(httpMsg) || httpMsg.Length < 100)
                {
                    AppendRichTextBox("未能获得光猫配置数据");
                }
                else
                {
                    AppendRichTextBox("获取光猫配置数据成功");
                    break;//成功获取网页数据
                }
            }

            //if (string.IsNullOrEmpty(httpMsg) || httpMsg.Contains("1,1,1,1,") == false) return false;//如果不能获得网页数据，则返回失败
            AppendRichTextBox(httpMsg);

            Dictionary<string, string> listValue = GetDictionary(httpMsg);//从网页上获取需要检查的信息

            //if (mac != enterMac)
            //{
            if (realMac.ToUpper().StartsWith(SharedData.YCD_MAC_EPON_START) || realMac.ToUpper().StartsWith(SharedData.YCD_MAC_GPON_START))
            {
                PRODUCT proW = new PRODUCT();
                proW.SetWhere();
                proW.YCD_MAC = realMac;
                proW.TEST_RESULT = "N";
                var selectProCount = MethodWcf.SelectProductCountClient(proW);
                if (selectProCount.result && selectProCount.message == "1")//测试失败的情况
                {
                    AppendRichTextBox("上道工序测试失败");
                    AppendRichTextBox("将光猫拿到信息检查工位重测");
                    SetControlText(labelWornMsg, "给语音信息检重测", true);

                    FinallyDone(enterMac);
                    return;
                }
                else//重号的情况
                {
                    //主机上的MAC为YCD_MAC
                    AppendRichTextBox("MAC地址重复！！！");
                    AppendRichTextBox("请将光猫给上个工序，贴新的MAC地址！");
                    SetControlText(labelWornMsg, "将光猫给信息检查，贴新MAC", true);


                    FinallyDone(enterMac);
                    return;
                }
            }

            if (realMac.Trim() != enterMac.Trim())
            {
                //提示重新扫描两次
                string againEnterMac = (string)this.Invoke(PublicData.enterMsgDelegate, _myFormNum, "MAC");

                if (againEnterMac != realMac)
                {
                    AppendRichTextBox("扫描MAC与主机MAC不一致");
                    AppendRichTextBox("请将MAC标签撕下，给到信息检查工位重新使用");
                    AppendRichTextBox("请将光猫恢复到工厂模式后，走信息写入流程");
                    SetControlText(labelWornMsg, "撕下MAC给语音信息检使用", true);

                    FinallyDone(enterMac);
                    return;
                }
                else
                {
                    PublicData.ListAddress.Remove(enterMac);
                    PublicData.ListAddress.Remove(againEnterMac);

                    FactotyCheck(againEnterMac);

                    return;
                }
            }

            //判断是否可以测试
            bool canTest = StationTestDll.StationTest.IfCanTest(enterMac, ref msg, _stationIp);

            AppendRichTextBox(msg);
            if (canTest == false)
            {
                //AppendRichTextBox(StationTestDll.StationTest.TcpErrorMsg);
                FinallyDone(enterMac);
                return;
            }

            //检查产品信息是否正确

            bool checkRet = CheckDeviceMsg(device, listValue, deviceType, out string checkMsg);

            if (checkRet == false)
            {
                AppendRichTextBox(checkMsg);
                SetControlText(this.labelWornMsg, checkMsg, true);
            }
            else
            {
                //更新产品的编译时间
                Device_Data dataW = new Device_Data();
                dataW.SetWhere();
                dataW.MACAddr = realMac;
                dataW.SetUpdate();
                dataW.BUILD_TIME = deviceType.BuildTime;

                MethodWcf.UpdateDeviceDataClient(dataW);//更新编译时间
            }

            bool saveLogResult = false;
            if (checkRet)
            {
                saveLogResult = StationTestDll.StationTest.SaveTestData(enterMac, checkRet, _log, ref msg, _stationIp);
                AppendRichTextBox(msg);
            }

            if (device.PONType == "EPON")
            {
                FinallyDone(enterMac, checkRet && saveLogResult, "E");
            }
            else
            {
                FinallyDone(enterMac, checkRet && saveLogResult, "G");
            }

            return;
        }

        private int portOffset = DateTime.Now.Second;
        /// <summary>
        /// 获取网页数据
        /// </summary>
        /// <returns></returns>
        private string GetModemMessage(Device_Type type)
        {
            //使用新的类YcdTelnetClass
            if (portOffset >= 800) portOffset = 0;
            portOffset++;

            string webKey = string.Empty;

            HttpArgs httpArgs = new HttpArgs
            {
                Url = "/cgi-bin/cgic_systeminfo.cgi",
            };

            if (type.DeviceType.Contains("PT952"))
            {
                httpArgs.Port = 80;
                httpArgs.Host = "192.168.1.1:80";
                webKey = type.ProcessName;
            }
            else if (type.DeviceType.Contains("CMCC"))
            {
                httpArgs.Port = 80;
                httpArgs.Host = "192.168.1.1:80";
                webKey = type.PluginRun;
            }
            else
            {
                httpArgs.Port = 8080;
                httpArgs.Host = "192.168.1.1:8080";
                webKey = type.PluginRun;
            }

            //使用新的方法获取网页数据
            bool hasKey = HttpBaseClass.GetHttpMsg(_localIp, _localPort + portOffset, _modemIp, httpArgs.Port, httpArgs, webKey, out string modemMsg);

            System.Threading.Thread.Sleep(300);

            if (hasKey == false) return string.Empty;

            return modemMsg;
        }

        /// <summary>
        /// 检查产品相关的出厂信息得出结果
        /// </summary>
        /// <param name="device"></param>
        /// <param name="dict"></param>
        /// <returns></returns>
        private bool CheckDeviceMsg(Device_Data device, Dictionary<string, string> dict, Device_Type type, out string message)
        {
            message = "";

            if (device == null || dict == null || type == null) { message = "升级固件,解析网页数据失败"; return false; }

            //写入信息到测试结果中

            //youhua_add_180102
            if (dict.TryGetValue("Manufacturer", out string value) && value == type.Manufacturer)
            {
                AppendRichTextBox("Manufacturer检查通过");
            }
            else
            {
                AppendRichTextBox("Manufacturer检查未通过");
                message = "恢复工厂重走信息检";
                return false;
            }

            //产品型号
            string productType = device.DeviceType.Replace(" ", "");
            if (productType.Contains("_"))
            {
                productType = productType.Substring(0, productType.IndexOf("_"));
            }

            if (dict.TryGetValue("ProductClass", out value) && value == productType)
            {
                AppendRichTextBox("ProductClass检查通过");
            }
            else
            {
                AppendRichTextBox("ProductClass检查未通过");
                message = "恢复工厂重走信息检";
                return false;
            }

            //硬件版本
            if (dict.TryGetValue("HWVersion", out value) && value == type.HWVersion)
            {
                AppendRichTextBox("HWVersion检查通过");
            }
            else
            {
                AppendRichTextBox("HWVersion检查未通过");
                message = "恢复工厂重走信息检";
                return false;
            }

            //软件版本
            if (dict.TryGetValue("SWVersion", out value) && value == type.SWVersionInside)
            {
                AppendRichTextBox("SWVersion检查通过");
            }
            else
            {
                AppendRichTextBox("SWVersion检查未通过");
                message = "固件升级,固件版本检查失败";
                return false;
            }

            //省份信息就检查
            if ((dict.TryGetValue("PROVINCE", out value) == false || string.IsNullOrEmpty(value))
                && string.IsNullOrEmpty(device.HW_PROVINCE_NAME))
            {
                AppendRichTextBox("数据库和网页中均无省份信息，未检查");
            }
            else if (dict.TryGetValue("PROVINCE", out value) && value == device.HW_PROVINCE_NAME)
            {
                AppendRichTextBox("PROVINCE检查通过");
            }
            else
            {
                AppendRichTextBox("PROVINCE检查未通过");
                message = "恢复工厂重走信息检";
                return false;
            }


            //MAC
            if (dict.TryGetValue("MAC", out value) && value == device.MACAddr)
            {
                AppendRichTextBox("MAC检查通过");
            }
            else
            {
                AppendRichTextBox("MAC检查未通过");
                message = "MAC地址检查失败";
                return false;
            }

            //光猫编码,light_model
#if true
            if (string.IsNullOrEmpty(device.LightModuleSN)
                && (dict.TryGetValue("light_model", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和光猫上light_model都为空，不用检查");
            }
            else

                if (dict.TryGetValue("light_model", out value) && value == device.LightModuleSN.Substring(0, 8) && string.IsNullOrEmpty(value) == false)
            {
                AppendRichTextBox("light_model检查通过");
            }
            else
            {
                AppendRichTextBox("light_model检查未通过");
                message = "恢复工厂重走信息检,light_model未通过";
                return false;
            }
#endif

            //OUI1
            //if (device.DeviceType.Contains("_RC") == false && device.DeviceType.Contains("PT926") == false)
            //{
            //兼容9603C版本
            if (dict.TryGetValue("OUI", out value) && value == device.OUI1)
            {
                AppendRichTextBox("OUI检查通过");
            }
            else
            {
                AppendRichTextBox("OUI检查未通过");
                message = "恢复工厂重走信息检,OUI检查失败";
                return false;
            }
            //}

            //OUI2
            if (dict.TryGetValue("SerialNum", out value) && value == device.OUI2)
            {
                AppendRichTextBox("SerialNum检查通过");
            }
            else
            {
                AppendRichTextBox("SerialNum检查未通过");
                message = "恢复工厂重走信息检";
                return false;
            }
            //xponMode
            if (dict.TryGetValue("xponMode", out value) && value == type.XPONMode)
            {
                AppendRichTextBox("xponMode检查通过");
            }
            else
            {
                AppendRichTextBox("xponMode检查未通过");
                message = "检查混料,XPONMode检查失败";
                return false;
            }

            //BOSA类型，1代表GPON，2代表EPON
            string mode = "2";

            //只有xpon为GPON时才检查SN号码，且GPONSN不为空
            if (device.PONType == "STIA")
            {
                mode = "1";

                //if (device.DeviceType.Contains("_RC") == false && device.DeviceType.Contains("PT926") == false)
                //{
                if (dict.TryGetValue("GPON_SN", out value) && value == device.XPON_SN)
                {
                    AppendRichTextBox("GPON_SN检查通过");
                }
                else
                {
                    AppendRichTextBox("GPON_SN检查未通过");
                    message = "检查混料，GPON_SN检查未通过";
                    return false;
                }
                //}
            }

            //Mode_只有R方案检查
            if (dict.TryGetValue("Mode", out value) && value == mode)
            {
                AppendRichTextBox("Mode检查通过");
            }
            else
            {
                AppendRichTextBox("Mode检查未通过");
                message = "检查混料,MODE检查未通过";
                return false;
            }

            //username
            if (dict.TryGetValue("username", out value) && value == device.WedUser)
            {
                AppendRichTextBox("username检查通过");
            }
            else
            {
                AppendRichTextBox("username检查未通过");
                message = "恢复工厂重走信息检,username未通过";
                return false;
            }
            //password
            if (dict.TryGetValue("web_passwd", out value) && value == device.WedPassword)
            {
                AppendRichTextBox("web_passwd检查通过");
            }
            else
            {
                AppendRichTextBox("web_passwd检查未通过");
                message = "恢复工厂重走信息检,web_passwd未通过";
                return false;
            }
            //SSID1
            if (dict.TryGetValue("SSID1", out value) && value == device.WIFI_SSID)
            {
                AppendRichTextBox("SSID1检查通过");
            }
            else
            {
                AppendRichTextBox("SSID1检查未通过");
                message = "恢复工厂重走信息检,username未通过";
                return false;
            }
            //SSID PWD
            if (dict.TryGetValue("WPAPSK1", out value) && value == device.WIFI_Password)
            {
                AppendRichTextBox("WPAPSK1检查通过");
            }
            else
            {
                AppendRichTextBox("WPAPSK1检查未通过");
                message = "恢复工厂重走信息检,WPAPSK1未通过";
                return false;
            }

            //SSID2检查规则，双向对比
            if (string.IsNullOrEmpty(device.ITV_SSID)
                && (dict.TryGetValue("SSID2", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和光猫上SSID2都为空，不用检查");
            }
            else

                if (dict.TryGetValue("SSID2", out value) && value == device.ITV_SSID && string.IsNullOrEmpty(value) == false)
            {
                AppendRichTextBox("SSID2检查通过");
            }
            else
            {
                AppendRichTextBox("SSID2检查未通过");
                message = "恢复工厂重走信息检,SSID2未通过";
                return false;
            }

            //SSID 2 PWD
            if (string.IsNullOrEmpty(device.ITV_Password)
                && (dict.TryGetValue("WPAPSK2", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和光猫上WPAPSK2都为空，不用检查");
            }
            else if (dict.TryGetValue("WPAPSK2", out value) && value == device.ITV_Password && string.IsNullOrEmpty(value) == false)
            {
                AppendRichTextBox("WPAPSK2检查通过");
            }
            else
            {
                AppendRichTextBox("WPAPSK2检查未通过");
                message = "恢复工厂重走信息检,WPAPSK2未通过";
                return false;
            }


            //IP
            if (string.IsNullOrEmpty(type.IP)
                && (dict.TryGetValue("IP", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页均无IP项目，未检查");
            }
            else if (dict.TryGetValue("IP", out value) && value == type.IP)
            {
                AppendRichTextBox("IP检查通过");
            }
            else
            {
                AppendRichTextBox("IP检查未通过");
                message = "固件升级";
                return false;
            }


            //wanTelnet
            if (dict.TryGetValue("WanTelnet", out value) && value == type.WlanTelnet)
            {
                AppendRichTextBox("Wan Telnet检查通过");
            }
            else
            {
                AppendRichTextBox("Wan Telnet检查未通过");
                message = "恢复出厂设置";
                return false;
            }

            //LanTelnet
            if (dict.TryGetValue("LanTelnet", out value) && value == type.LanTelnet)
            {
                AppendRichTextBox("Lan Telnet检查通过");
            }
            else
            {
                AppendRichTextBox("Lan Telnet检查未通过");
                message = "恢复出厂设置";
                return false;
            }

            //checksum，信息校验，R方案需要检查checkSum

            if (dict.TryGetValue("securitycheck", out value) && value == type.securitycheck)
            {
                AppendRichTextBox("security check检查通过");
            }
            else
            {
                AppendRichTextBox("security check 检查未通过");
                message = "恢复工厂重走信息检,信息安全检查未通过";
                return false;
            }

            //BOB4
            if (string.IsNullOrEmpty(type.BoBtable4check)
                && (dict.TryGetValue("BoBtable4check", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无BoBtable4check，未检查");
            }
            else
                if (dict.TryGetValue("BoBtable4check", out value) && value == type.BoBtable4check)
            {
                AppendRichTextBox("BoBtable4check检查通过");
            }
            else
            {
                AppendRichTextBox("BoBtable4check 检查未通过");
                message = "恢复工厂重走信息检,信息安全检查未通过";
                return false;
            }

            //BOB5
            if (string.IsNullOrEmpty(type.BoBtable5check)
                && (dict.TryGetValue("BoBtable5check", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无BoBtable5check，未检查");
            }
            else if (dict.TryGetValue("BoBtable5check", out value) && value == type.BoBtable5check)
            {
                AppendRichTextBox("BoBtable5check检查通过");
            }
            else
            {
                AppendRichTextBox("BoBtable5check 检查未通过");
                message = "恢复工厂重走信息检,信息安全检查未通过";
                return false;
            }

            //PROCESS NAME
            if (string.IsNullOrEmpty(type.ProcessName)
                && (dict.TryGetValue("ProcessName", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无ProcessName，未检查");
            }
            else
                if (dict.TryGetValue("ProcessName", out value) && value.Contains(type.ProcessName))
            {
                AppendRichTextBox("ProcessName检查通过");
            }
            else
            {
                AppendRichTextBox("ProcessName检查未通过");
                message = "恢复工厂重走信息检,信息安全检查未通过";
                return false;
            }

            if (string.IsNullOrEmpty(type.ProductAgingResult)
                && (dict.TryGetValue("ProductAgingResult", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无ProductAgingResult，未检查");
            }
            else if (dict.TryGetValue("ProductAgingResult", out value) && value == type.ProductAgingResult)
            {
                AppendRichTextBox("ProductAgingResult检查通过");
            }
            else
            {
                AppendRichTextBox("ProductAgingResult检查未通过");
                message = "重新老化，ProductAgingResult检查未通过";
                return false;
            }


            //WanConnect
            if (string.IsNullOrEmpty(type.WanConnect)
                && (dict.TryGetValue("WanConnect", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无WanConnect，未检查");
            }
            else
                if (dict.TryGetValue("WanConnect", out value) && value == type.WanConnect)
            {
                AppendRichTextBox("WanConnect检查通过");
            }
            else
            {
                AppendRichTextBox("WanConnect检查未通过");
                message = "固件升级，WanConnect检查未通过";
                return false;
            }


            //PluginNum

            if (string.IsNullOrEmpty(type.PluginNum)
                && (dict.TryGetValue("PluginNum", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无PluginNum，未检查");
            }
            else
                if (dict.TryGetValue("PluginNum", out value) && value == type.PluginNum)
            {
                AppendRichTextBox("PluginNum检查通过");
            }
            else
            {
                AppendRichTextBox("PluginNum检查未通过");
                message = "插件升级，PluginNum检查未通过";
                return false;
            }


            //pluginName
            if (string.IsNullOrEmpty(type.PluginName)
                && (dict.TryGetValue("PluginName", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无PluginName，未检查");
            }
            else if (dict.TryGetValue("PluginName", out value) && value == type.PluginName)
            {
                AppendRichTextBox("PluginName检查通过");
            }
            else if (value.Length == type.PluginName.Length)
            {
                string[] items = value.Split(',');
                foreach (string i in items)
                {
                    if (type.PluginName.Contains(i) == false)
                    {
                        message = "插件升级，PluginName检查未通过";
                        return false;
                    }
                }
                AppendRichTextBox("PluginName检查通过");
            }
            else
            {
                AppendRichTextBox("PluginName检查未通过");
                message = "插件升级，PluginName检查未通过";
                return false;
            }

            //pluginRun
            if (string.IsNullOrEmpty(type.PluginRun)
                && (dict.TryGetValue("PluginRun", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无PluginRun，未检查");
            }
            else
                if (dict.TryGetValue("PluginRun", out value) && value == type.PluginRun)
            {
                AppendRichTextBox("PluginRun检查通过");
            }
            else
            {
                AppendRichTextBox("PluginRun检查未通过");
                message = "插件升级，PluginRun检查未通过";
                return false;
            }

            //Framework1
            if (string.IsNullOrEmpty(type.FrameWork1)
                && (dict.TryGetValue("Framework1", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无Framework1，未检查");
            }
            else
                if (dict.TryGetValue("Framework1", out value) && value == type.FrameWork1)
            {
                AppendRichTextBox("Framework1检查通过");
            }
            else
            {
                AppendRichTextBox("Framework1检查未通过");
                message = "插件升级，Framework1检查未通过";
                return false;
            }

            //Framework2
            if (string.IsNullOrEmpty(type.FrameWork2)
                && (dict.TryGetValue("Framework2", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无Framework2，未检查");
            }
            else
                if (dict.TryGetValue("Framework2", out value) && value == type.FrameWork2)
            {
                AppendRichTextBox("Framework2检查通过");
            }
            else
            {
                AppendRichTextBox("Framework2检查未通过");
                message = "插件升级,Framework2检查未通过";
                return false;
            }

            //APPS
            if (string.IsNullOrEmpty(type.APPS)
                && (dict.TryGetValue("APPS", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无APPS，未检查");
            }
            else
                if (dict.TryGetValue("APPS", out value) && value == type.APPS)
            {
                AppendRichTextBox("APPS检查通过");
            }
            else
            {
                AppendRichTextBox("APPS检查未通过");
                message = "插件升级，APPS检查未通过";
                return false;
            }


            //Framework(active)
            if (string.IsNullOrEmpty(type.FrameworkActive)
              && (dict.TryGetValue("Framework(active)", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无Framework(active)，未检查");
            }
            else
              if (dict.TryGetValue("Framework(active)", out value) && value == type.FrameworkActive)
            {
                AppendRichTextBox("Framework (active)检查通过");
            }
            else
            {
                AppendRichTextBox("Framework (active)检查未通过");
                message = "插件升级，Framework (active)检查未通过";
                return false;
            }


            //URL
            if (string.IsNullOrEmpty(type.URL)
                && (dict.TryGetValue("URL", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无URL，未检查");
            }
            else
                if (dict.TryGetValue("URL", out value) && value == type.URL)
            {
                AppendRichTextBox("URL检查通过");
            }
            else
            {
                AppendRichTextBox("URL检查未通过");
                message = "固件升级，URL检查未通过";
                return false;
            }

            //RelativeURL
            if (string.IsNullOrEmpty(type.RelativeURL)
                && (dict.TryGetValue("RelativeURL", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无RelativeURL，未检查");
            }
            else
                if (dict.TryGetValue("RelativeURL", out value) && value == type.RelativeURL)
            {
                AppendRichTextBox("Relative URL检查通过");
            }
            else
            {
                AppendRichTextBox("Relative URL检查未通过");
                message = "固件升级，Relative URL检查未通过";
                return false;
            }

            //LastChangedRev
            if (string.IsNullOrEmpty(type.SWVersion)
                && (dict.TryGetValue("LastChangedRev", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无LastChangedRev，未检查");
            }
            else
                if (dict.TryGetValue("LastChangedRev", out value) && value == type.SWVersion)
            {
                AppendRichTextBox("Last Changed Rev检查通过");
            }
            else
            {
                AppendRichTextBox("Last Changed Rev检查未通过");
                message = "固件升级，Last Changed Rev检查未通过";
                return false;
            }

            //LastChangedData
            if (string.IsNullOrEmpty(type.LastChangedDate)
                && (dict.TryGetValue("LastChangedDate", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无LastChangedDate，未检查");
            }
            else
                if (dict.TryGetValue("LastChangedDate", out value) && value == type.LastChangedDate)
            {
                AppendRichTextBox("Last Changed Date检查通过");
            }
            else
            {
                AppendRichTextBox("Last Changed Date检查未通过");
                message = "固件升级，Last Changed Date检查未通过";
                return false;
            }

            //Compile Time
            if (string.IsNullOrEmpty(type.BuildTime)
                && (dict.TryGetValue("CompileTime", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无CompileTime，未检查");
            }
            else
                if (dict.TryGetValue("CompileTime", out value) && value == type.BuildTime.Replace(" ", "").Replace(":", ""))
            {
                AppendRichTextBox("Compile Time检查通过");
            }
            else
            {
                AppendRichTextBox("Compile Time检查未通过");
                message = "固件升级，Compile Time检查未通过";
                return false;
            }

            //iptvProduct
            if ( (dict.TryGetValue("iptvProduct", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("网页上无iptvProduct，未检查");
            }
            else
                if (dict.TryGetValue("iptvProduct", out value) && value == device.DeviceType)
            {
                AppendRichTextBox("iptvProduct检查通过");
            }
            else
            {
                AppendRichTextBox("iptvProduct检查未通过");
                message = "重走语言信息检查";
                return false;
            }

            //iptvMAC
            if (string.IsNullOrEmpty(device.ITV_MAC)
                && (dict.TryGetValue("iptvMAC", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无iptvMAC，未检查");
            }
            else
                if (dict.TryGetValue("iptvMAC", out value) && value ==device.ITV_MAC)
            {
                AppendRichTextBox("iptvMAC检查通过");
            }
            else
            {
                AppendRichTextBox("iptvMAC检查未通过");
                message = "重走语言信息检查，iptvMAC检查未通过";
                return false;
            }

            //iptvStbID
            if (string.IsNullOrEmpty(device.STBID)
                && (dict.TryGetValue("iptvStbID", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无iptvStbID，未检查");
            }
            else
                if (dict.TryGetValue("iptvStbID", out value) && value ==device.STBID)
            {
                AppendRichTextBox("iptvStbID检查通过");
            }
            else
            {
                AppendRichTextBox("iptvStbID检查未通过");
                message = "重走语言信息检查，iptvStbID检查未通过";
                return false;
            }

            //iptvSerialNum
            if (string.IsNullOrEmpty(device.STBID)
                && (dict.TryGetValue("iptvSerialNum", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无iptvSerialNum，未检查");
            }
            else
                if (dict.TryGetValue("iptvSerialNum", out value) && value == device.STBID)
            {
                AppendRichTextBox("iptvSerialNum检查通过");
            }
            else
            {
                AppendRichTextBox("iptvSerialNum检查未通过");
                message = "重走语言信息检查，iptvSerialNum检查未通过";
                return false;
            }

            //iptvHWVersion
            if (string.IsNullOrEmpty(type.iptvHWVersion)
                && (dict.TryGetValue("iptvHWVersion", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无iptvHWVersion，未检查");
            }
            else
                if (dict.TryGetValue("iptvHWVersion", out value) && value == type.iptvHWVersion)
            {
                AppendRichTextBox("iptvHWVersion检查通过");
            }
            else
            {
                AppendRichTextBox("iptvHWVersion检查未通过");
                message = "固件升级，iptvHWVersion检查未通过";
                return false;
            }

            //iptvSWVersion
            if (string.IsNullOrEmpty(type.iptvSWVersion)
                && (dict.TryGetValue("iptvSWVersion", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无iptvSWVersion，未检查");
            }
            else
                if (dict.TryGetValue("iptvSWVersion", out value) && value == type.iptvSWVersion)
            {
                AppendRichTextBox("iptvSWVersion检查通过");
            }
            else
            {
                AppendRichTextBox("iptvSWVersion检查未通过");
                message = "固件升级，iptvSWVersion检查未通过";
                return false;
            }

            //iptvCompileTIme
            if (string.IsNullOrEmpty(type.iptvCompileTime)
                && (dict.TryGetValue("iptvCompileTime", out value) == false || string.IsNullOrEmpty(value)))
            {
                AppendRichTextBox("数据库和网页上均无iptvCompileTime，未检查");
            }
            else
                if (dict.TryGetValue("iptvCompileTime", out value) && value == type.iptvCompileTime)
            {
                AppendRichTextBox("iptvCompileTime检查通过");
            }
            else
            {
                AppendRichTextBox("iptvCompileTime检查未通过");
                message = "固件升级，iptvCompileTime检查未通过";
                return false;
            }

            message = "检查通过";

            return true;
        }

        /// <summary>
        /// 将光猫数据从字符串转换为键值对
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetDictionary(string msg)
        {
            if (string.IsNullOrEmpty(msg)) return null;

            var dict = new Dictionary<string, string>();
            //去除信息中的所有空格
            msg = msg.Replace(" ", "");
            //去掉所有横杠
            //msg = msg.Replace("-", "");

            //将信息按照换行符分割，并去除掉头尾的空白字符
            var listMsg = msg.Split('\n');

            //继续将信息按照冒号分割成键值对
            for (int i = 0; i < listMsg.Length; i++)
            {
                var temp = listMsg[i].Split(':');

                //获取key和value
                string key = null;
                string value = null;

                if (temp.Length == 2)
                {
                    key = temp[0].Trim();
                    value = temp[1].Trim();
                }
                else if (temp.Length > 2)
                {
                    key = temp[0].Trim();

                    for (int j = 1; j < temp.Length; j++)
                    {
                        value += temp[j].Trim();
                    }
                }

                if (key == null) continue;

                //增加键值对
                if (dict.ContainsKey(key) == false)
                {
                    dict.Add(key, value);
                }
                else
                {
                    dict.TryGetValue(key, out string keyValue);

                    keyValue += "," + value;
                    dict.Remove(key);
                    dict.Add(key, keyValue);
                }
            }
            return dict;
        }

        /// <summary>
        /// 获取产品类型信息
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private Device_Type GetDeviceType(string type, string province)
        {
            var device = (from t in _listType
                          where t.DeviceType == type && t.PROVINCE == province
                          select t).FirstOrDefault();

            return device;
        }


        //将信息写入信息窗口
        private void AppendRichTextBox(string value/*, bool hasEnter = true*/)
        {
            if (this.richTextBoxMsg.InvokeRequired)
            {
                Action<string> d = new Action<string>(AppendRichTextBox);
                Invoke(d, new object[] { value });
            }
            else
            {
                if (value == null) return;
                //if (this.richTextBoxMsg.TextLength >= 5000)
                //    lock (PublicData.LOCKOBJUI)
                //        this.richTextBoxMsg.Clear();

                value = value.Replace("\0", "");
                lock (PublicData.LOCKOBJUI)
                    this.richTextBoxMsg.AppendText(value + "\r\n");

                WriteLog(value);
            }
        }

        private void ClearText(Control con)
        {
            if (this.InvokeRequired)
            {
                Action<Control> d = new Action<Control>(ClearText);
                Invoke(d, con);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                    con.Text = null;
            }
        }


        /// <summary>
        /// 连接并登陆光猫，返回类，若为空则链接失败
        /// </summary>
        /// <returns></returns>
        //private YcdTelnetClass TelnetModem()
        //{
        //    //使用新的类YcdTelnetClass
        //    if (portOffset >= 800) portOffset = 0;
        //    portOffset++;

        //    Console.WriteLine("portOffset is: " + portOffset);

        //    YcdTelnetClass telnet = new YcdTelnetClass(_modemIp, _localIp, _localPort + portOffset);
        //    if (telnet.Connect() == false)
        //    {
        //        return null;
        //    }

        //    System.Threading.Thread.Sleep(500);


        //    string msg;
        //    if (telnet.GetReturnMsg("login",out msg))
        //    {
        //        AppendRichTextBox("输入用户名称……");
        //        telnet.Send(_modemUser);
        //    }
        //    else
        //    {
        //        telnet.Send("exit");
        //        telnet.Close();
        //        return null;
        //    }


        //    //System.Threading.Thread.Sleep(3000);

        //    if (telnet.GetReturnMsg("Password:",out msg))
        //    {
        //        AppendRichTextBox("输入用户密码中……");
        //        telnet.Send(_modemPwd);
        //    }
        //    else
        //    {
        //        telnet.Send("exit");
        //        telnet.Close();
        //        return null;
        //    }

        //    bool hasKey= telnet.GetReturnMsg("#",out msg);

        //    if (hasKey==false) return null;

        //    AppendRichTextBox(msg);

        //    return telnet;
        //}

        //设置结果
        //private void SetTestResult(bool result, string msg = null)
        //{
        //    if (LabelTestState.InvokeRequired)
        //    {
        //        Action<bool, string> d = new Action<bool, string>(SetTestResult);
        //        Invoke(d, result, msg);
        //    }
        //    else
        //    {
        //        if (result && msg == null)
        //        {
        //            this.LabelTestState.ForeColor = Color.Green;
        //            this.LabelTestState.Text = "PASS";
        //        }
        //        else if (result == false && msg == null)
        //        {
        //            this.LabelTestState.ForeColor = Color.Red;
        //            this.LabelTestState.Text = "FAIL";
        //        }
        //        else if (msg != null && result == false)
        //        {
        //            this.LabelTestState.ForeColor = Color.Black;
        //            this.LabelTestState.Text = msg;
        //        }
        //        else if (msg != null && result)
        //        {
        //            this.LabelTestState.ForeColor = Color.BlueViolet;
        //            this.LabelTestState.Text = msg;
        //        }
        //    }
        //}

        /// <summary>
        /// 获得MAC地址
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        private string GetModemMac(YcdTelnetClass tel)
        {
            if (tel == null) return null;

            tel.Send("ifconfig br0");

            System.Threading.Thread.Sleep(500);

            bool hasKey = tel.GetReturnMsg("addr", out string msg);

            if (string.IsNullOrEmpty(msg))
            {
                return null;
            }

            AppendRichTextBox(msg);
            string[] msgArray = msg.Split(' ');
            //从msg中得到MAC地址
            string macMsg = (from s in msgArray
                             where s.Contains(":") && s.Length == 17
                             select s).FirstOrDefault();

            //获得MAC地址字符串
            //获得MAC地址字符串
            if (macMsg != null) macMsg = macMsg.Replace(":", "");

            return macMsg;
        }

        /// <summary>
        /// 写MAC地址
        /// </summary>
        /// <param name="mac"></param>
        private void SetTextBoxProductMac(string mac)
        {
            if (this.textBoxMAC.InvokeRequired)
            {
                Action<string> d = new Action<string>(SetTextBoxProductMac);
                Invoke(d, mac);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                    this.textBoxMAC.Text = mac;
            }
        }

        private void SetControlText(Control con, string text = null, bool isVisable = false)
        {
            if (this.InvokeRequired)
            {
                Action<Control, string, bool> d = new Action<Control, string, bool>(SetControlText);
                Invoke(d, con, text, isVisable);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                {
                    con.Visible = isVisable;
                    con.Text = text;
                }
            }
        }

        private void SetControlText(Control con, string text, Color col)
        {
            if (this.InvokeRequired)
            {
                Action<Control, string, Color> d = new Action<Control, string, Color>(SetControlText);
                Invoke(d, con, text, col);
            }
            else
            {
                lock (PublicData.LOCKOBJUI)
                {
                    if (string.IsNullOrEmpty(text) == false) con.Text = text;
                    con.ForeColor = col;
                }
            }
        }

        private Device_Data GetProductEdition(string mac)
        {
            var deviceW = new Device_Data();
            deviceW.SetWhere();

            deviceW.MACAddr = mac;

            var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);
            if (selectDevice.result)
                return selectDevice.value[0];
            else
                return null;

            ////给device赋值
            //if (selectDevice.result) device = selectDevice.value[0];
            //else device = null;

            //if (selectDevice.result == false || selectDevice.result && selectDevice.value[0].DeviceType.Trim() == "PT924 G")
            //{
            //    return SharedData.EDITION_MTK;
            //}
            //else
            //{
            //    return SharedData.EDITION_R;
            //}
        }

        /// <summary>
        /// 写log信息
        /// </summary>
        /// <param name="msg"></param>
        private void WriteLog(string msg)
        {
            lock (lockLog)
                _log = string.Format("{0}{1}\r\n", _log, msg);
        }

        private void RichTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            lock (PublicData.LOCKOBJUI)
            {
                richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
                richTextBoxMsg.ScrollToCaret();
            }
        }

        private void TextBoxMAC_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.textBoxMAC.ReadOnly) return;
            //扫描入MAC地址
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                if (this.textBoxMAC.Text.Trim().Length != 12)
                {
                    AppendRichTextBox("MAC地址不为12位数");
                    this.textBoxMAC.Clear();
                    this.textBoxMAC.Focus();
                }
                else
                {
                    //判断MAC是否已经绑定过SN号码，如果已经绑定了，则直接开始写入信息
                    this.textBoxMAC.ReadOnly = true;

                    Action<string> d = new Action<string>(FactotyCheck);
                    d.BeginInvoke(null, null, null);

                }
            }
            else if ((e.KeyChar >= 'a' && e.KeyChar <= 'f')
                || (e.KeyChar >= 'A' && e.KeyChar <= 'F')
                || (e.KeyChar >= '0' && e.KeyChar <= '9')
                || (e.KeyChar == 8))
            {
                //判断是否位16进制字符，将小写全部转为大写
                e.Handled = false;
            }
            else
            {
                MessageBox.Show("只能输入数字和A-F");
                e.Handled = true;
            }
        }

    }
}
